<template>
  <view class="fill-bg" :style="[fillBgStyle]">
    <canvas
      v-if="!watermarkBgUrl"
      class="file-watermark"
      canvas-id="file-watermark"
    />
  </view>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import { sleep } from '@/utils/helper/uniHelper'

@Component({ name: 'Watermark' })
export default class Watermark extends Vue {
  public watermarkBgUrl = ''

  get fillBgStyle(): Partial<CSSStyleDeclaration> {
    return {
      background: this.watermarkBgUrl
        ? `url(${this.watermarkBgUrl}) left top repeat`
        : 'transparent'
    }
  }

  onReady() {
    this.initWatermark()
  }

  initWatermark() {
    // const {
    //   realName = '',
    //   currentIp = '',
    //   tenantName = ''
    // } = userStore.authInfo ?? {}
    // const text1 = `${realName} ${currentIp}`

    const ctx = uni.createCanvasContext('file-watermark', this)
    ctx.setTextAlign('center')
    ctx.font = '13px sans-serif'
    ctx.setFillStyle('rgba(122,126,142,0.3)')

    // 设置画布基准点，后续操作都将基于此
    ctx.translate(80, 80)
    // 旋转-45度
    ctx.rotate((-30 * Math.PI) / 180)
    ctx.fillText('text1', 0, -10)
    ctx.fillText('tenantName', 0, 10)
    ctx.draw(true)

    const repeatSave = async () => {
      if (!this.watermarkBgUrl) {
        await sleep(8)
        uni.canvasToTempFilePath(
          {
            canvasId: 'file-watermark',
            destWidth: 190,
            destHeight: 190,
            fileType: 'png',
            success: (res) => {
              if (res?.tempFilePath) {
                this.watermarkBgUrl = res.tempFilePath
              } else {
                repeatSave()
              }
            },
            fail: () => repeatSave()
          },
          this
        )
      }
    }
    repeatSave()
  }
}
</script>

<style lang="scss" scoped>
.fill-bg {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  pointer-events: none;
  z-index: 10000;
}

.file-watermark {
  position: fixed;
  left: 0;
  right: 0;
  width: 160px;
  height: 160px;
  transform: translate3d(100vw, 100vh, 100px);
}
</style>
